package com.wjk.kylin.id.core.entity;

import java.util.concurrent.atomic.AtomicLong;

public class SegmentId {
    private long maxId;
    private long loadingId;//提前去请求获取id
    private AtomicLong currentId;
    private int delta;

    public Result nextId() {
        long id = this.currentId.addAndGet(this.delta);
        if (id > this.maxId) {
            //3:已经使用完id
            return new Result(ResultCode.OVER.getCode(), id);
        } else {
            //2: 提前去加载下一次的id请求
            //1：正常使用
            return id >= this.loadingId ? new Result(ResultCode.LOADING.getCode(), id) : new Result(ResultCode.NORMAL.getCode(), id);
        }
    }

    /**
     * 判断当前id 是否超过最大id
     *
     * @return
     */
    public boolean isUse() {
        return this.currentId.get() <= this.maxId;
    }

    public long getMaxId() {
        return this.maxId;
    }

    public void setMaxId(long maxId) {
        this.maxId = maxId;
    }

    public long getLoadingId() {
        return this.loadingId;
    }

    public void setLoadingId(long loadingId) {
        this.loadingId = loadingId;
    }

    public AtomicLong getCurrentId() {
        return this.currentId;
    }

    public void setCurrentId(AtomicLong currentId) {
        this.currentId = currentId;
    }

    public int getDelta() {
        return this.delta;
    }

    public void setDelta(int delta) {
        this.delta = delta;
    }

    @Override
    public String toString() {
        return "SegmentId{" +
                "maxId=" + maxId +
                ", loadingId=" + loadingId +
                ", currentId=" + currentId +
                ", delta=" + delta +
                '}';
    }
}
